package yanShiRenWu;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class OrderDelay implements Delayed {

    private String orderId;
    private long timeOut;

    public OrderDelay(String orderId, long timeOut) {
        this.orderId = orderId;
        this.timeOut = timeOut;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        //距离你自定义的超时时间
        return unit.convert(timeOut - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        if (o == this) {
            return 0;
        }
        OrderDelay o1 = (OrderDelay) o;
        long d = getDelay(TimeUnit.NANOSECONDS) - (o1.getDelay(TimeUnit.NANOSECONDS));
        return d == 0 ? 0 : (d < 0 ? -1 : 1);
    }

    void print() {
        System.out.println(this.orderId + " <<--即将删除");
    }
}

class DelayedQueueTest {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("000000001");
        list.add("000000002");
        list.add("000000003");
        list.add("000000004");
        list.add("000000005");

        DelayQueue<OrderDelay> delayQueue = new DelayQueue<>();
        long start = System.currentTimeMillis();

        for (int i = 0; i < 5; i++) {
            //Poll():获取并移除队列的超时元素，没有则返回空
            //take():获取并移除队列的超时元素，如果没有则wait当前线程，直到有元素满足超时条件，返回结果。
            delayQueue.put(new OrderDelay(list.get(i), TimeUnit.NANOSECONDS.convert(3, TimeUnit.SECONDS)));

            try {
                delayQueue.take().print();
                System.out.println((System.currentTimeMillis() - start) + "ms后~~~");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}





























